# -*- coding: utf-8 -*-
# author yzs
# date 2018-12-17
#
# 相对排序
# Description
# Given two array A1[] and A2[], sort A1 in such a way that the relative order among the elements will be same as those
# in A2. For the elements not present in A2. Append them at last in sorted order.
# It is also given that the number of elements in A2[] are smaller than or equal to number of elements in A1[] and A2[]
# has all distinct elements.
# Input:A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} A2[] = {2, 1, 8, 3} Output: A1[] = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}
# Since 2 is present first in A2[], all occurrences of 2s should appear first in A[], then all occurrences 1s as
# 1 comes after 2 in A[]. Next all occurrences of 8 and then all occurrences of 3.
# Finally we print all those elements of A1[] that are not present in A2[]
# Constraints:1 ≤ T ≤ 501 ≤ M ≤ 501 ≤ N ≤ 10 & N ≤ M1 ≤ A1[i], A2[i] ≤ 1000
# Input
# The first line of input contains an integer T denoting the number of test cases.
# The first line of each test case is M and N.
# M is the number of elements in A1 and N is the number of elements in A2.
# The second line of each test case contains M elements. The third line of each test case contains N elements.
# Output
# Print the sorted array according order defined by another array.
# Sample Input 1 
# 1
# 11 4
# 2 1 2 5 7 1 9 3 6 8 8
# 2 1 8 3
# Sample Output 1
# 2 2 1 1 8 8 3 5 6 7 9


def related_sort(array_A,array_B):
    array_B_len = len(array_B)
    count = [0]*array_B_len
    other_array = []
    for i in array_A:
        try:
            index = array_B.index(i)
            count[index] += 1
        except:
            other_array.append(i)
    for m in range(array_B_len):
        for n in range(count[m]):
            print(array_B[m], end=' ')
    other_array.sort()
    print(" ".join(str(k) for k in other_array))


T = int(input().strip())
for i in range(T):
    data = list(map(int, input().strip().split()))
    M,N = data[0],data[1]
    A1 = list(map(int, input().strip().split()))
    A1 = A1[:M]
    A2 = list(map(int, input().strip().split()))
    A2 = A2[:N]
    related_sort(A1,A2)